package com.ziytek.web.citizen.service;

import com.google.gson.Gson;
import com.ziytek.web.citizen.config.caffeine.CaffeineUtil;
import com.ziytek.web.citizen.event.CommandFirstDataEvent;
import com.ziytek.web.citizen.model.bean.CommandFirst;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * @author fenghx
 **/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @__(@Autowired))
public class CommandFirstDataService {
    private final Gson gson;

    public void commandFirstData(CommandFirstDataEvent event) {
        Assert.notNull(event, "CommandFirstDataEvent event is null");
        Assert.notNull(event.getCells(), "CommandFirstDataEvent cells list is null");
        Assert.notNull(event.getCabinetNo(), "CommandFirstDataEvent cabinetNo is null");
        Assert.notNull(event.getCommandIssued(), "CommandFirstDataEvent command  is null");
        Assert.notNull(event.getBoardAddress(), "CommandFirstDataEvent board list is null");

        log.info("工步下发成功后,第一帧上送数据处理CommandFirstDataEventListener,cabinetNo:{},boardAddress:{},cells:{},command:{}", event.getCabinetNo(),
                gson.toJson(event.getBoardAddress()), gson.toJson(event.getCells()), gson.toJson(event.getCommandIssued()));
        var cells = event.getCells();
        var cab = event.getCabinetNo();
        var board = event.getBoardAddress();
        var command = event.getCommandIssued();
        var commandFirst = new CommandFirst();
        BeanUtils.copyProperties(command, commandFirst);
        var td = Thread.startVirtualThread(() -> {
            for (var bd : board) {
                for (var cl : cells) {
                    var key = CaffeineUtil.FIRST_DATA_CACHE_PREFIX + CaffeineUtil.getCacheKey(cab, bd, cl);
                    CaffeineUtil.set(key, commandFirst, 50);
                    //log.info("CommandFirstDataEventListener caffeine set,key:{},cd:{}", key, command);
                }
            }
        });

        try {
            td.join();
        } catch (Exception e) {
            log.error("工步下发成功后,第一帧上送数据处理异常CommandFirstDataEventListener,cabinetNo:{},boardAddress:{},cells:{}", event.getCabinetNo(), event.getBoardAddress(), event.getCells());
        }


        var cacheKey = CaffeineUtil.FIRST_DATA_ALL_CACHE_PREFIX + cab + "_" + command.getBoardNo() + "_" + command.getChannelNo();
        if (command.isSingleChannel()) {
            cacheKey = CaffeineUtil.FIRST_DATA_SINGLE_CACHE_PREFIX + cab + "_" + command.getBoardNo() + "_" + command.getChannelNo();
        }

        // 设置需要判断第一帧数据缓存
        //CaffeineUtil.deleteStartWith(CaffeineUtil.FIRST_DATA_ALL_CACHE_PREFIX + cab);
        CaffeineUtil.set(cacheKey, command, 50);
    }
}
